﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Graffiti.Core;

namespace GraffitiExtras.Utility
{
    public class AjaxExtras : IHttpHandler
    {
        private const string objectManagerName = "GraffitiExtras.Widgets.PollManager::PollObject";
        private Poll currentPoll;

        // Methods
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.RequestType == "POST")
            { 
                string pollSubmitted = context.Request.Form["PollSubmitted"];
                if (pollSubmitted != null)
                {
                    currentPoll = ObjectManager.Get<Poll>(objectManagerName);

                    if (pollSubmitted == "1" && !currentPoll.IPAddresses.Contains(context.Request.UserHostAddress))
                    {
                        try
                        {

                            if (currentPoll != null)
                            {
                                currentPoll.PollItems.Find(delegate(PollItem gpi) { return gpi.PollItemGuid == context.Request.Form["GPI::PollItem"]; }).PollItemValue++;
                                currentPoll.IPAddresses.Add(context.Request.UserHostAddress);

                                ObjectManager.Save(currentPoll, objectManagerName);

                                context.Response.Write("Thanks for voting!");
                            }
                            else
                                context.Response.Write("Sorry, There was an error: GPE101");
                        }
                        catch(Exception ex)
                        {
                            Log.Error("Poll Manager Widget ", ex.Message + ex.StackTrace);
                        }
                    }
                    else
                        context.Response.Write("Sorry, there was an error.");
                }
                else
                    context.Response.Write("Sorry, there was an error.");
            }
        }

        // Properties
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

}

